package com.zrb.mobile;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

public class User_change_Password extends BaseActivity implements OnClickListener  {

	ImageView btnAccountclear, btnPwdclear,btnAccountclear1,btnAccountclear2,btnAccountclear3,rightView3,rightView1,rightView2;
	
	EditText editTextpwd,editRepeatpwd,editCode;
	Tip progTip;
	Button btn_send;
	MyCount mc;
	//String phoneNum;
	private String mobile;
	private RelativeLayout notify_view;
  	private TextView notify_view_text;
  	Handler mhandler = new Handler();
  	private final int SPLASH_DISPLAY_LENGHT = 2000;
  	
  	boolean ischangepwd=false;
  	String oldpwdstr;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

	 
		setContentView(R.layout.u_center_resetpwd);
	
		//changepwd
		if (bundle != null)
			restoreSelf(bundle);
		else {
			ischangepwd=this.getIntent().getBooleanExtra("changepwd", false);
			oldpwdstr=this.getIntent().getStringExtra("oldpassword");
			mobile = this.getIntent().getStringExtra("mobile");
		}
	 	initView();
 	}

	@Override
	protected  void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putBoolean("changepwd", ischangepwd);
        outState.putString("mobile", mobile);
        outState.putString("oldpassword", oldpwdstr);
    }

    private void restoreSelf(Bundle savedInstanceState)
    {
    	 ischangepwd = savedInstanceState.getBoolean("changepwd");
   	     mobile = savedInstanceState.getString("mobile");
   	     oldpwdstr= savedInstanceState.getString("oldpassword");
    }
	
	private void initView() {
		
		//Toast提示框
		notify_view = (RelativeLayout)this.findViewById(R.id.notify_view);
		notify_view_text = (TextView)this.findViewById(R.id.notify_view_text);
		
		TextView txtTitle=	(TextView)this.findViewById(R.id.txt_title);
		txtTitle.setText(ischangepwd ?"修改密码":"找回密码");
		
		this.findViewById(R.id.layout_verifycode).setVisibility(ischangepwd ? View.GONE:View.VISIBLE);
	 
		
		TextView rightHite=	(TextView)this.findViewById(R.id.right_title);
		rightHite.setVisibility(ischangepwd ?View.GONE: View.VISIBLE);
		rightHite.setText("完成");
		rightHite.setOnClickListener(this);
		
		View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
 
		btn_send=(Button)this.findViewById(R.id.send_btn);
		btn_send.setOnClickListener(this);
		btn_send.setEnabled(ischangepwd);
 		
		//this.findViewById(R.id.button_register).setOnClickListener(this);
		
		editTextpwd=(EditText)this.findViewById(R.id.edit_pwd);
		editRepeatpwd=(EditText)this.findViewById(R.id.edit_repeatpwd);
		editCode=(EditText)this.findViewById(R.id.edit_verifycode);
 		
		if(!ischangepwd) {
			mc = new MyCount(60000, 1000);  
		    mc.start();  
		}
		else{
	 		btn_send.setText("完成");
	 		editCode.setText("zrb888");
		}
			
		
		rightView1 = (ImageView) this.findViewById(R.id.phone_btn_right);
		rightView2 = (ImageView) this.findViewById(R.id.phone_btn_right1);
		rightView3 = (ImageView) this.findViewById(R.id.phone_btn_right2);
		
		editTextpwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {  
			    @Override  
			    public void onFocusChange(View v, boolean hasFocus) {
			    	if( !TextUtils.isEmpty(editTextpwd.getText()) ){
			    		 if( editTextpwd.getText().length()!= 0  && !hasFocus && CommonUtil.checkPassword(editTextpwd.getText().toString())) {
			    			 	btnAccountclear1.setVisibility(View.GONE);
					        	rightView1.setVisibility(View.VISIBLE);
							} else {
								btnAccountclear1.setVisibility(View.VISIBLE);
					        	rightView1.setVisibility(View.GONE);
							}
			    	}
			    }
			});
		
		editRepeatpwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {  
		    @Override  
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if( !TextUtils.isEmpty(editRepeatpwd.getText())){
		    		 if( editTextpwd.getText().length()!= 0  && !hasFocus && CommonUtil.checkPassword(editRepeatpwd.getText().toString())) {
		    			 	btnAccountclear2.setVisibility(View.GONE);
				        	rightView2.setVisibility(View.VISIBLE);
						} else {
							btnAccountclear2.setVisibility(View.VISIBLE);
				        	rightView2.setVisibility(View.GONE);
						}
		    	}
		    }
		});
		
		editCode.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {  
		    @Override  
		    public void onFocusChange(View v, boolean hasFocus) {
		    	if( !TextUtils.isEmpty(editCode.getText()) ){
		    		 if( editTextpwd.getText().length()!= 0  && !hasFocus ) {
		    			 	btnAccountclear3.setVisibility(View.GONE);
				        	rightView3.setVisibility(View.VISIBLE);
						} else {
							btnAccountclear3.setVisibility(View.VISIBLE);
				        	rightView3.setVisibility(View.GONE);
						}
		    	}
		    }
		});
		
		
		btnAccountclear1 = (ImageView) this.findViewById(R.id.phone_btn_clean);
		btnAccountclear1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				editTextpwd.setText("");
			}
		});
		editTextpwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if( s.length() != 0){
					btnAccountclear1.setVisibility(View.VISIBLE);
				}else{
					btnAccountclear1.setVisibility(View.GONE);
				}
					
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		
		btnAccountclear2 = (ImageView) this.findViewById(R.id.phone_btn_clean1);
		btnAccountclear2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				editRepeatpwd.setText("");
			}
		});
		editRepeatpwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if( s.length() != 0){
					btnAccountclear2.setVisibility(View.VISIBLE);
				}else{
					btnAccountclear2.setVisibility(View.GONE);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		
		btnAccountclear3 = (ImageView) this.findViewById(R.id.phone_btn_clean2);
		btnAccountclear3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				editCode.setText("");
			}
		});
		editCode.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if( s.length() != 0){
					btnAccountclear3.setVisibility(View.VISIBLE);
				}else{
					btnAccountclear3.setVisibility(View.GONE);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	     
 	}
	
	/*定义一个倒计时的内部类*/  
    class MyCount extends CountDownTimer {     
        public MyCount(long millisInFuture, long countDownInterval) {     
            super(millisInFuture, countDownInterval);     
        }     
        @Override     
        public void onFinish() { 
        	btn_send.setEnabled(true);
        	btn_send.setText("获取验证码");        
        }     
        @Override     
        public void onTick(long millisUntilFinished) {     
        	btn_send.setText("重新取验证码(" + millisUntilFinished / 1000 + ")秒");     
           // Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有显示时间延迟       
        }    
    }  

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
	 
		case R.id.right_title:
			// Share();
			changePwd();
 			break;
		case R.id.send_btn:
 			if(ischangepwd){
 				changePwd();
				return;
			}
			btn_send.setEnabled(false);
			getvalidateCode();
			break;
		}
 	}
 
	private void getvalidateCode(){
 		
		// if(!isPhoneOk(true,true)) return ;
 		if(mc==null)
			mc = new MyCount(60000, 1000);  
        mc.start();  
        RequestParams param = new RequestParams();
		 param.put("mobile", mobile);
//	 	 String url=String.format("register/sendSMSRegister?mobile=%1$s", phoneNum);
		 ZrbRestClient.post("register/sendSMSFindPW", param,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						showToast("fail", User_change_Password.this);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
 					   String results = new String(arg2);
						try {
							Gson gson = new Gson();
							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
							if(tmpDto.res==1)
								
							  return ;
							else
								initNotify("发送验证码出错");
 
						 } catch (Exception e) {
					     	showToast( "fail:"+e.getMessage(),User_change_Password.this);
						}
					}
				});
	}
	
 
	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在修改中...", true,
					true);
		else
			progTip.Show("正在修改中...");
	}

	private void changePwd() {
		
		String pwdStr=this.editTextpwd.getText()==null ? "":this.editTextpwd.getText().toString();
		String RepeatpwdStr=this.editRepeatpwd.getText()==null ? "":this.editRepeatpwd.getText().toString();
		String verifyCodeStr=this.editCode.getText()==null ? "":this.editCode.getText().toString();
		
		if (TextUtils.isEmpty(pwdStr)) {
			initNotify("密码不能为空");
			return;
		}
		if (!CommonUtil.checkPassword(pwdStr)) {
			initNotify("密码不符合规则");
			return;
		}
 		if (!RepeatpwdStr.equals(pwdStr)) {
			initNotify("密码输入不一致");
			return;
		}
 		if (TextUtils.isEmpty(verifyCodeStr)) {
			initNotify("验证码不能为空");
			return;
		}
		
 		showloading();
 		
 		/*		RequestParams param = new RequestParams();
		 param.put("mobile", mobile);
		 param.put("passWord", pwdStr);
		 param.put("smsCode", verifyCodeStr);
		 */
		String url=String.format("register/changePWord?mobile=%1$s&smsCode=%2$s&passWord=%3$s", mobile,verifyCodeStr,pwdStr);
 		if(ischangepwd) 
			 url=String.format("user/changePWord?passWord=%1$s&newpassWord=%2$s&zrb_front_ut=%3$s", oldpwdstr,pwdStr,AppSetting.curUser.zrb_front_ut);
		 ///user/changePWord?passWord=1234567&newpassWord=1234567&zrb_front_ut=306d8e1d90f87e7f55c075e959ede8c7
		ZrbRestClient.get(url, null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						showToast("fail", User_change_Password.this);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						String results = new String(arg2);

						try {

							Gson gson = new Gson();
 							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
							if( tmpDto.res == 1){
								showToast( "密码修改成功",User_change_Password.this);
								new Handler().postDelayed(new Runnable() {
									@Override
									public void run() {
										
										if(ischangepwd) {
	 										User_change_Password.this.setResult(android.app.Activity.RESULT_OK);
											User_change_Password.this.finish();
											return;
										}
										Intent it = new Intent(User_change_Password.this, User_phone_login.class);
										it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(it);
										User_change_Password.this.finish();
		                                finish();
									}
								}, SPLASH_DISPLAY_LENGHT);
							}else{
								initNotify(tmpDto.msg);
							}
  						} catch (Exception e) {

							showToast( "fail:"+e.getMessage(),User_change_Password.this);
							System.out.println("eeee!!!!" + e.getMessage());

						}

					}
				});

	}
 	 
	private void showToast(String msg,Context mcontext){
 		Toast toast = Toast.makeText(mcontext, msg,Toast.LENGTH_SHORT );//duration
	    toast.setGravity(Gravity.TOP, 0,CommonUtil.dip2px(mcontext, 80));
	    toast.show();
 	}
	
	/* 初始化通知栏目*/
	private void initNotify(final String msg) {
		mhandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				notify_view_text.setText(msg);
				notify_view.setVisibility(View.VISIBLE);
				mhandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						notify_view.setVisibility(View.GONE);
					}
				}, 2000);
			}
		}, 1000);
	}
}